// 发送单条短信示例
// 引入 nodemailer   kbdqrpkfdaizdihj  授权码
const nodemailer = require('nodemailer') // 记得在当前文件夹执行npm install nodemailer后才能使用  
const db = uniCloud.database();
exports.main = async (event, context) => {

	// 根据event传过来的emailFormat的内容来判断发送的是什么邮箱 目前只有qq邮箱和163邮箱
	// jbxjjy@163.com  测试邮箱
	
	if (!event.email) {
		return {
			code: 400,
			message: "邮箱为空,无法发送"
		}
	} else {

		let send = async (email) => {
			let transporter = nodemailer.createTransport({
				host: 'smtp.qq.com',
				secureConnection: true,
				port: 465,
				secure: true,
				auth: {
					user: '2317770710@qq.com',
					pass: 'wrfrrqitbufedjbe'
				}
			})
			let info = await transporter.sendMail({
				from: '2317770710@qq.com',
				to: email,
				subject: event.subject,
				html: event.centent,
				text: '文本'
			})
			return info.messageId
		}

		if (event.email == 'all') {
			let userInfo = await db.collection('userList').get()

			for (let i = 0; i < userInfo.data.length; i++) {
				let item = userInfo.data[i]
				console.log(item.email , '邮箱');
				if (item.isSendEmailAllowed && item._id != event.userId) {
					await send(item.email)
				}
			}
			return {
				code: 200,
				message: '发送成功'
			}
		} else {
			let messageId = await send(event.email)
			console.log(messageId , 'messageId');
			if (messageId) {
				return {
					code: 200,
					message: '发送成功'
				}
			} else {
				return {
					code: 500,
					message: '发送失败'
				}
			}
		}



	}

}